package com.shbaiche.bifenba.ui.data;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.cpoopc.scrollablelayoutlib.ScrollableLayout;
import com.google.gson.Gson;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.model.Event;
import com.shbaiche.bifenba.model.base.BoolValue;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.data.TeamFollowMessage;
import com.shbaiche.bifenba.model.data.TeamInfoMessage;
import com.shbaiche.bifenba.model.match.MatchesLineupMessage;
import com.shbaiche.bifenba.model.user.FollowCancelMessage;
import com.shbaiche.bifenba.model.user.FollowUpdateMessage;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseActivity;
import com.shbaiche.bifenba.ui.base.BaseScrollAbleFragment;
import com.shbaiche.bifenba.ui.base.WebActivity;
import com.shbaiche.bifenba.ui.home.CategoryTabStrip;
import com.shbaiche.bifenba.ui.my.CollectionFragment;
import com.shbaiche.bifenba.ui.my.FollowTeamFragment;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;
import com.shbaiche.bifenba.view.CircularImage;
import com.shbaiche.bifenba.view.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroid.event.BusFactory;
import cn.droidlover.xdroidbase.base.XFragmentAdapter;
import cn.droidlover.xdroidbase.imageloader.ILFactory;
import cn.droidlover.xdroidbase.router.Router;
import okhttp3.Call;


/**
 * 球队详情
 */

public class DataTeamDetailActivity extends BaseActivity {
    public static final String KEY_TEAMID="teamId";
    public static final String KEY_GAMETYPE="gameType";

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.scrollableLayout)
    ScrollableLayout scrollableLayout;

    @BindView(R.id.category_strip)
    CategoryTabStrip tabs;

    @BindView(R.id.view_pager)
    NoScrollViewPager pager;

    @BindView(R.id.iv_logo)
    CircularImage ivLogo;

    @BindView(R.id.tv_name)
    TextView tvName;

    @BindView(R.id.tv_desc)
    TextView tvDesc;

    @BindView(R.id.btn_follow)
    SuperButton btnFollow;


    List<Fragment> fragmentList = new ArrayList<>();
    XFragmentAdapter adapter;

    // 球队编号
    private String teamId;

    // 比赛类型: 1足球 0篮球
    private String gameType;

    TeamInfoMessage teamInfo;

    private Dialog dg;

    @Override
    public void initData(Bundle savedInstanceState) {
        teamId = getIntent().getStringExtra(KEY_TEAMID);
        gameType = getIntent().getStringExtra(KEY_GAMETYPE);

        Log.e("t",gameType+":"+teamId);

        dg = new Dialog(this);
        dg.setContentView(R.layout.view_loading);

        if(!TextUtils.isEmpty(teamId) && !TextUtils.isEmpty(gameType)){
            loadData();


        }else{
            ToastUtil.show("参数异常");
            finish();
        }



    }




    public void loadData() {
        TeamInfoMessage message = new TeamInfoMessage();
        message.setTeamId(teamId);
        message.setGameType(gameType);
        message.setPassport(App.getPassport());

        NetApi.teamInfo(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());

            }

            @Override
            public void onResponse(TransMessage response, int id) {

                TeamInfoMessage result =new Gson().fromJson(response.getMessage(),TeamInfoMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null){
                        Log.e("t","onResponse");

                        setData(result);

                    }
                }else{
                    Log.e("t","onResponse getCode "+response.getCode());
                    ToastUtil.show(result.getMessage());
                }
            }
        });
    }

    private void setData(TeamInfoMessage message){
        if(message!=null){
            teamInfo = message;
            Log.e("t",teamInfo.toString());
            if(message.getIsFollow() == BoolValue.YES){
                btnFollow.setText("已关注");
            }else{
                btnFollow.setText("+关注");
            }
            btnFollow.setVisibility(View.VISIBLE);

            ILFactory.getLoader().loadNet(ivLogo, message.getTeam().getPhoto(), null);
            tvName.setText(message.getTeam().getName());
            tvDesc.setText(message.getTeam().getEstablishDate()+"/"+message.getTeam().getCountry()+"/"+message.getTeam().getCity());

            if(fragmentList.size()== 0){
                initFragments(message);
            }

        }
    }

    @OnClick({
            R.id.btn_follow
    })
    public void clickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_follow:
                if(teamInfo!=null){
                    if(teamInfo.getIsFollow() == BoolValue.YES){
                        cancelFollow();
                    }else{
                        postFollow();
                    }
                }

                break;

        }
    }

    public void postFollow() {
        if(App.getPassport()==null){
            ToastUtil.show("请先登录");
            return;
        }
        dg.show();
        TeamFollowMessage message = new TeamFollowMessage();
        message.setPassport(App.getPassport());
        message.setTeamId(teamId);
        message.setGameType(gameType);
        message.setType(FollowUpdateMessage.FollowType.TEAM);

        NetApi.teamFollow(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();
            }

            @Override
            public void onResponse(TransMessage response, int id) {
                dg.dismiss();
                TeamFollowMessage result =new Gson().fromJson(response.getMessage(),TeamFollowMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null){
                        Log.e("t","onResponse");
                        loadData();
                        ToastUtil.show(result.getMessage());

                    }
                }else{
                    Log.e("t","onResponse getCode "+response.getCode());
                    ToastUtil.show(result.getMessage());
                }
            }
        });
    }

    public void cancelFollow() {
        dg.show();
        FollowCancelMessage message = new FollowCancelMessage();
        message.setPassport(App.getPassport());
        message.setFollowId(teamId);
        message.setGameType(gameType);
        message.setType(FollowUpdateMessage.FollowType.TEAM);

        NetApi.followCancel(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();

            }

            @Override
            public void onResponse(TransMessage response, int id) {
                dg.dismiss();
                FollowCancelMessage result =new Gson().fromJson(response.getMessage(),FollowCancelMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null){
                        Log.e("t","onResponse");
                        loadData();
                        ToastUtil.show(result.getMessage());

                    }
                }else{
                    Log.e("t","onResponse getCode "+response.getCode());
                    ToastUtil.show(result.getMessage());
                }
            }
        });
    }



    private void initFragments(TeamInfoMessage message){
        fragmentList.clear();
        Bundle bundle = new Bundle();
        bundle.putSerializable("message",message);
        bundle.putSerializable("data",message.getTeam());
        bundle.putString("teamId",teamId);
        bundle.putString("gameType",gameType);


        DataTeamDetailDynamicFragment fragmentDynamic = new DataTeamDetailDynamicFragment();
        fragmentDynamic.setArguments(bundle);
        fragmentList.add(fragmentDynamic);

        DataScheduleFragment fragmenSchedule = new DataScheduleFragment();
        fragmenSchedule.setArguments(bundle);
        fragmentList.add(fragmenSchedule);

        DataTeamDetailMemberFragment fragmentMember = new DataTeamDetailMemberFragment();
        fragmentMember.setArguments(bundle);
        fragmentList.add(fragmentMember);

        DataTeamDetailInfoFragment fragmentInfo = new DataTeamDetailInfoFragment();
        fragmentInfo.setArguments(bundle);
        fragmentList.add(fragmentInfo);

        if (adapter == null) {
            adapter = new XFragmentAdapter(getSupportFragmentManager(), fragmentList, new String[]{"动态","赛程","球员","资料"});
        }

        pager.setAdapter(adapter);

        tabs.setViewPager(pager);
        tabs.setAdaptive(true);
    }



    @Override
    public void setListener() {

    }

//    @OnClick({
//            R.id.about_stv_weixin
//    })
//    public void clickEvent(View view) {
//        switch (view.getId()) {
//
//            case R.id.about_stv_weixin:
//                WebActivity.launch(context, "https://github.com/limedroid/XDroid", "XDroid");
//                break;
//        }
//    }

    public static void launch(Activity activity) {
        Router.newIntent()
                .from(activity)
                .to(DataTeamDetailActivity.class)
                .data(new Bundle())
                .launch();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_team_detail;
    }

    @Override
    public void setToolbar() {
        initToolbar(toolbar,"球队");
    }

}
